import { useUserStore } from '@/stores/user'

// 验证手机号
export const validatePhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

// 验证密码 (6-20位)
export const validatePassword = (password) => {
  return password.length >= 6 && password.length <= 20
}

// 验证码倒计时
export const countDown = (count, callback) => {
  let timer = setInterval(() => {
    count--
    callback(count)
    if (count <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  return timer
}

// 显示提示
export const showToast = (title, icon = 'none') => {
  uni.showToast({
    title,
    icon,
    duration: 2000
  })
}

// 检查登录状态
export const checkLogin = () => {
  const userStore = useUserStore()
  if (!userStore.isLogin) {
    uni.redirectTo({
      url: '/pages/login/login'
    })
	uni.showToast({
		title:'暂未登录，请先登录',
		icon:'none'
	})
    return false
  }
  return true
}

// 格式化日期
export const formatDate = (date, fmt = 'YYYY-MM-DD') => {
  if (!date) return ''
  date = new Date(date)
  const o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : (`00${o[k]}`).substr((`${o[k]}`).length)
      )
    }
  }
  return fmt
}

// 防抖函数
export const debounce = (fn, delay = 500) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 节流函数
export const throttle = (fn, delay = 500) => {
  let lastTime = 0
  return function (...args) {
    const now = Date.now()
    if (now - lastTime > delay) {
      fn.apply(this, args)
      lastTime = now
    }
  }
}
